<template>
  <div class="app-container">
    <div class="chart-title">档案管理</div>
    <div class="chart-content">
      <div class="filter-title">
        <el-form label-position="right">
          <el-form-item>
            <el-input
              v-model="listQuery.name"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('goods.name')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
          <div
            class="search-button"
            @click="handleFilter"
          >
            <img src="@/assets/images/bg_search@2x.png" />
          </div>
          <div
            class="search-button"
            @click="handleRefresh"
          >
            <img src="@/assets/images/bg_reset@2x.png" />
          </div>
        </el-form>
        <div class="filter-right">
          <div
            class="add-button"
            @click="handleCreate"
          >
            <img src="@/assets/images/icon_add@2x.png" />
            <span>新建</span>
          </div>
        </div>
      </div>
      <div class="chart-list">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255,255,255,0.2)"
          border
          fit
          highlight-current-row
          style="width: 100%min-height:1000px"
        >
          <el-table-column
            fixed="left"
            align="center"
            :label="$t('table.id')"
            width="65"
          >
            <template slot-scope="scope">
              <span>{{
                (listQuery.page - 1) * listQuery.limit + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('goods.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('goods.thumbnail')"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 120px; height: 120px"
                :src="scope.row.main_img"
                fit="contain"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('goods.weight')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.weight }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('goods.referCost')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.cost_price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('goods.referBook')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.front_price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('goods.referSpot')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.buy_price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('table.actions')"
            fixed="right"
          >
            <template slot-scope="scope">
              <div class="operat-button">
                <div
                  class="read-img"
                  @click="handleRead(scope.row)"
                >
                  <img src="@/assets/images/read@2x.png" />
                </div>
                <div
                  class="read-img"
                  @click="handleModifyStatus(scope.row, 'deleted')"
                >
                  <img src="@/assets/images/delete@2x.png" />
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
      <!-- 编辑 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        v-loading="dialogLoading"
        element-loading-text="正在上传中 请稍后！"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="120px"
          size="small"
        >
          <div class="pops">
            <div class="information-title">
              <span class="icon-title"></span>
              <span>基础信息:</span>
            </div>
            <div class="pops-content">
              <div class="pops-item">
                <div class="pops-left">
                  <el-form-item
                    :label="$t('goods.name') + ' :'"
                    prop="name"
                  >
                    <el-input
                      v-model="temp.name"
                      :readonly="dialogStatus !== 'create' ? true : false"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    :label="$t('goods.weight') + ' :'"
                    prop="weight"
                  >
                    <el-input-number
                      class="left-number"
                      v-model="temp.weight"
                      :controls="false"
                      :disabled="dialogStatus === 'read' ? true : false"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item
                    :label="$t('goods.description') + ' :'"
                    prop="description"
                  >
                    <el-input
                      v-model="temp.description"
                      type="textarea"
                      :autosize="{ minRows: 2, maxRows: 6 }"
                      :readonly="dialogStatus === 'read' ? true : false"
                    ></el-input>
                  </el-form-item>
                </div>
                <div class="pops-right">
                  <el-form-item
                    :label="$t('goods.referCost') + ' :'"
                    prop="cost_price"
                  >
                    <el-input-number
                      class="left-number"
                      v-model="temp.cost_price"
                      :controls="false"
                      :disabled="dialogStatus === 'read' ? true : false"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item
                    :label="$t('goods.referBook') + ' :'"
                    prop="front_price"
                  >
                    <el-input-number
                      class="left-number"
                      v-model="temp.front_price"
                      :controls="false"
                      :disabled="dialogStatus === 'read' ? true : false"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item
                    :label="$t('goods.referSpot') + ' :'"
                    prop="buy_price"
                  >
                    <el-input-number
                      class="left-number"
                      v-model="temp.buy_price"
                      :controls="false"
                      :disabled="dialogStatus === 'read' ? true : false"
                    ></el-input-number>
                  </el-form-item>
                </div>
              </div>
              <div>
                <el-form-item
                  :label="$t('goods.thumbnail') + ' :'"
                  prop="main_img"
                >
                  <div class="avatar-uploader">
                    <div
                      v-if="temp.main_img"
                      class="main-img"
                    >
                      <el-image
                        style="width: 100%; height: 100%"
                        :src="temp.main_img"
                        fit="contain"
                      ></el-image>
                      <span class="img-cover">
                        <span @click="showImg(temp.main_img)"><i class="el-icon-zoom-in"></i></span>
                        <span
                          v-if="dialogStatus !== 'read'"
                          @click="removeImg('main_img')"
                        ><i class="el-icon-delete"></i></span>
                      </span>
                    </div>
                    <el-upload
                      v-else
                      class="update-pic-icon"
                      action="#"
                      :show-file-list="false"
                      :http-request="e => {return updatePicture(e, 'main_img');}"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </el-form-item>
                <el-form-item
                  :label="$t('goods.detailsImg') + ' :'"
                  prop="details_img"
                >
                  <div class="detail-img-list">
                    <div
                      class="detail-img"
                      v-for="(item, index) in detailImgList"
                      :key="index"
                    >
                      <el-image
                        style="width: 100%; height: 100%"
                        :src="item"
                        fit="contain"
                      ></el-image>
                      <span class="img-cover">
                        <span @click="showImg(item)"><i class="el-icon-zoom-in"></i></span>
                        <span
                          v-if="dialogStatus !== 'read'"
                          @click="removeImg('details_img', index)"
                        ><i class="el-icon-delete"></i></span>
                      </span>
                    </div>
                    <div
                      v-show="this.detailImgList.length < 9 && dialogStatus !== 'read'"
                      class="detail-img avatar-uploader"
                    >
                      <el-upload
                        class="update-pic-icon"
                        action="#"
                        :show-file-list="false"
                        :http-request="
                          e => {return updatePicture(e, 'details_img');}"
                      >
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
            <div>
              <el-form-item
                :label="$t('goods.details') + ' :'"
                prop="details"
              >
                <div style="padding-right:20px">
                  <el-card style="height: 610px;">
                    <quill-editor
                      v-model="temp.details"
                      ref="myQuillEditor"
                      style="height: 500px;"
                      :disabled="dialogStatus === 'read' ? true : false"
                      :options="quillOption"
                    >
                    </quill-editor>
                  </el-card>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer between-space"
        >
          <div>
            <el-button
              v-show="dialogStatus == 'read'"
              type="primary"
              @click="handleEdit"
            >{{ $t("table.edit") }}</el-button>
          </div>
          <div>
            <el-button @click="dialogFormVisible = false">{{
              $t("table.cancel")
            }}</el-button>
            <el-button
              v-if="dialogStatus == 'create'"
              type="primary"
              :disabled="!createDisabled"
              @click="createData"
            >{{ $t("table.confirm") }}</el-button>
            <el-button
              v-else-if="dialogStatus == 'edit'"
              type="primary"
              :disabled="!updateDisabled"
              @click="updateData"
            >{{ $t("table.confirm") }}</el-button>
            <el-button
              v-else
              type="primary"
              @click="dialogFormVisible = false"
            >{{ $t("table.confirm") }}</el-button>
          </div>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="dialogVisible">
        <img
          width="100%"
          :src="dialogImageUrl"
          alt=""
        />
      </el-dialog>
    </div>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
import { getToken } from "@/utils/auth"; // get token from cookie
import { quillEditor } from "vue-quill-editor";
import quillConfig from "@/utils/quill-config.js";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  name: "ProductArchive",
  components: {
    quillEditor,
    "drop-down-select": dropDownSelect
  },
  data() {
    const validateName = (rule, value, callback) => {
      // return false
      if (value && value.toString().length > 0) {
        if (value && value.toString().length > 20) {
          callback(new Error("名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error("名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号")
            );
          }
        }
      } else {
        callback(new Error("请填写名称"));
      }
    };
    const validateDescription = (rule, value, callback) => {
      if (value && value.toString().length > 5000) {
        callback(new Error("餐品介绍不得大于500个字符"));
      } else {
        callback();
      }
    };
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      dialogLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        name: ""
      },
      temp: {
        id: undefined,
        name: "",
        code: undefined,
        itoc_id: undefined,
        itoc_name: "",
        supplier_id: undefined,
        supplier_name: "",
        main_img: "",
        details_img: "",
        details: "",
        description: "",
        cost_price: undefined,
        front_price: undefined,
        buy_price: undefined
      },
      fileList: [],
      transferFile: [],
      detailImgList: [],
      mainTransferFile: "",
      uploaded: [],
      deleteDtail: [],
      dialogImageUrl: "",
      upde: false,
      dialogVisible: false,
      disabled: false,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        name: [{ required: true, trigger: "blur", validator: validateName }],
        weight: [
          { required: true, message: "请填写商品重量", trigger: "blur" }
        ],
        description: [{ trigger: "blur", validator: validateDescription }],
        main_img: [
          { required: true, message: "请上传缩略图", trigger: "change" }
        ]
      },
      createDisabled: true,
      updateDisabled: true,
      supplierOptions: [],
      supplierCount: undefined,
      itocOptions: [],
      itocCount: undefined,
      pageSize: 20,
      optionProps: {
        value: "id",
        label: "name"
      },
      content: null,
      quillOption: quillConfig
    };
  },
  created() {
    const token = getToken();
    if (
      token &&
      !this.$store.state.socket.loginTransition &&
      !this.$store.state.socket.loginAccount
    ) {
      this.tokenLogin(token);
    }
    this.getList();
  },
  methods: {
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        name: "",
        code: "",
        supplier_name: "",
        itoc_name: ""
      };
      this.getList();
    },
    // 获取商品列表
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page,
        name: this.listQuery.name ? this.listQuery.name : ""
      };
      const path = {
        app: "archives",
        api: "api_goods_index_getList",
        version: "1.0",
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 打开查看弹窗
    handleRead(row) {
      this.detailImgList = row.details_img.split(",");
      this.uploaded = this.detailImgList.length;
      console.log('已上传图片长度')
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "read";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleEdit() {
      this.dialogStatus = "edit";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        code: undefined,
        itoc_id: undefined,
        itoc_name: "",
        supplier_id: undefined,
        supplier_name: "",
        main_img: "",
        details_img: "",
        details: "",
        description: "",
        cost_price: undefined,
        front_price: undefined,
        buy_price: undefined
      };
      this.fileList = [];
      this.transferFile = [];
      this.detailImgList = [];
      this.mainTransferFile = "";
      this.deleteDtail = [];
      this.uploaded = 0;
    },
    // 添加商品档案
    updateImg(file, callback) {
      const video = new FormData();
      video.append("video", file);
      this.updateFile(video, result => {
        if (result.data.code === 0) {
          this.$message.error(result.data.message);
          return false;
        } else {
          callback(result.data.data.video_url);
        }
      });
    },
    changeData(callback) {
      let main_img = "";
      let detail_img = [];

      const transferFile = this.transferFile;
      const lengthCount = transferFile.length;
      const _this = this;
      console.log('this.transferFile', this.transferFile, lengthCount)
      // 判断主图是否更新
      if (this.mainTransferFile) {
        this.updateImg(this.mainTransferFile, res => {
          main_img = res;
          if (lengthCount > 0) {
            let j = 0;
            for (var i = 0; i < lengthCount; i++) {
              _this.updateImg(transferFile[i], result => {
                detail_img.push(result);
                j++;
                if (j === lengthCount) {
                  console.log('详情图更新', main_img, detail_img)
                  callback(main_img, detail_img);
                }
              });
            }
          } else {
            console.log('详情图未更新', main_img, detail_img)
            callback(main_img, detail_img);
          }
        });
      } else {
        if (lengthCount > 0) {
          let j = 0;
          for (var i = 0; i < lengthCount; i++) {
            _this.updateImg(transferFile[i], result => {
              detail_img.push(result);
              j++;
              if (j === lengthCount) {
                console.log('详情图更新2', main_img, detail_img)
                callback(main_img, detail_img);
              }
            });
          }
        } else {
          console.log('详情图未更新2', main_img, detail_img)
          callback(main_img, detail_img);
        }
      }
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.dialogLoading = true;
          const _this = this;
          _this.changeData((main_img, detail_img) => {
            if (_this.deleteDtail.length > 0) {
              _this.deleteDtail.forEach(element => {
                const index = element.lastIndexOf("/");
                const str = element.substring(index + 1, element.length);
                const video_name = { video_name: str };
                _this.deleteFile(video_name, result => {
                  this.sendCreate(main_img, detail_img);
                });
              });
            } else {
              _this.sendCreate(main_img, detail_img);
            }
          });
        }
      });
    },
    sendCreate(main_img, detail_img) {
      if (!main_img) {
        main_img = this.temp.main_img;
      }
      if (detail_img) {
        detail_img = this.detailImgList
          .slice(0, this.uploaded)
          .concat(detail_img);
      }
      const new_detail_img = detail_img.join(",");
      if (this.createDisabled) {
        this.createDisabled = false;
        const path = {
          app: "goods",
          api: "api_goods_index_add",
          version: "1.0",
          type: 2,
          data: {
            name: this.temp.name ? this.temp.name : "",
            main_img: main_img,
            description: this.temp.description ? this.temp.description : "",
            details: this.temp.details ? this.temp.details : "",
            details_img: new_detail_img || "",
            cost_price: this.temp.cost_price ? this.temp.cost_price : "",
            front_price: this.temp.front_price ? this.temp.front_price : "",
            buy_price: this.temp.buy_price ? this.temp.buy_price : "",
            weight: this.temp.weight ? this.temp.weight : ""
          }
        };
        this.socketApi.sendSock(JSON.stringify(path), res => {
          if (res) {
            this.socketData(res);
          }
          setTimeout(() => {
            this.createDisabled = true;
          }, 1000);
        });
      }
    },
    sendUpdate(main_img, detail_img) {
      if (!main_img) {
        main_img = this.temp.main_img;
      }
      if (detail_img) {
        detail_img = this.detailImgList.slice(0, this.uploaded).concat(detail_img);
      }
      const new_detail_img = detail_img.join(",");
      if (this.createDisabled) {
        this.createDisabled = false;
        const path = {
          app: "goods",
          api: "api_goods_index_edit",
          version: "1.0",
          type: 2,
          data: {
            id: this.temp.id ? this.temp.id : "",
            main_img: main_img,
            description: this.temp.description ? this.temp.description : "",
            details: this.temp.details ? this.temp.details : "",
            details_img: new_detail_img || "",
            cost_price: this.temp.cost_price ? this.temp.cost_price : "",
            front_price: this.temp.front_price ? this.temp.front_price : "",
            buy_price: this.temp.buy_price ? this.temp.buy_price : "",
            weight: this.temp.weight ? this.temp.weight : ""
          }
        };
        console.log('编辑', JSON.stringify(path))
        this.socketApi.sendSock(JSON.stringify(path), res => {
          if (res) {
            this.socketData(res);
          }
          setTimeout(() => {
            this.createDisabled = true;
          }, 1000);
        });
      }
    },
    // 更新商品档案
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.dialogLoading = true;
          if (this.updateDisabled) {
            const _this = this;
            console.log('提交更新商品')
            _this.changeData((main_img, detail_img) => {
              if (_this.deleteDtail.length > 0) {
                _this.deleteDtail.forEach(element => {
                  const index = element.lastIndexOf("/");
                  const str = element.substring(index + 1, element.length);
                  const video_name = { video_name: str };
                  _this.deleteFile(video_name, result => {
                    this.sendUpdate(main_img, detail_img);
                  });
                });
              } else {
                _this.sendUpdate(main_img, detail_img);
              }
            });
          }
        }
      });
    },
    handleModifyStatus(row) {
      this.$confirm("此操作将永久删除该商品信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const path = {
            app: "archives",
            api: "api_goods_index_delete",
            version: "1.0",
            data: {
              id: row.id
            }
          };
          this.socketApi.sendSock(JSON.stringify(path), res => {
            if (res) {
              this.socketData(res);
            } else {
              this.$message.error(" 删除失败 ");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 图片超出限制提示
    exceedLimit() {
      this.$message.error("最多上传9张详情图");
    },
    // 图片预览
    showImg(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    // 删除详情图
    removeImg(name, index = "") {
      if (name === "main_img") {
        this.mainTransferFile = "";
        this.temp.main_img = "";
      } else if (name === "details_img") {
        if (index < this.uploaded) {
          this.deleteDtail.push(this.detailImgList[index]);
          this.uploaded--;
        } else {
          this.transferFile.splice(index, 1);
        }
        this.detailImgList.splice(index, 1);
      }
      console.log('删除完后已上传图片长度', this.uploaded)
    },
    updatePicture(element, name) {
      if (name === "main_img") {
        this.mainTransferFile = element.file;
        this.temp.main_img = window.URL.createObjectURL(element.file);
      } else if (name === "details_img") {
        this.transferFile.push(element.file);
        this.detailImgList.push(window.URL.createObjectURL(element.file)); // imgURL就是你的图片的本地路径，两部就能解决问题
      }
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.dialogLoading = false;
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            });
          } else if (resj.api === "api_goods_index_getList") {
            this.total = resj.count;
            this.list = resj.data;
            this.listLoading = false;
          } else if (resj.api === "api_goods_index_add") {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.dialogLoading = false;
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_goods_index_edit") {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
            this.dialogLoading = false;
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_goods_index_delete") {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          }
        }
      }
    }
  }
};
</script>
<style scoped>
.detail-img-list {
  display: flex;
}
.detail-img {
  width: 72px;
  height: 72px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(204, 204, 204, 1);
  border-radius: 4px;
  position: relative;
}
.detail-img-list .detail-img:not(:first-child) {
  margin-left: 16px;
}
.update-pic-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}
.main-img {
  width: 100%;
  height: 100%;
}
</style>
